<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-row>
        <el-button type="primary" @click="addRolesDialog = true"
          >添加角色</el-button
        >
      </el-row>
      <!-- 列表 -->
      <el-table :data="rolesData" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template v-slot:default="scope">
            <el-row
              v-for="item in scope.row.children"
              :key="item.id"
              class="scoperow"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="tagClose(scope.row, item.id)">{{
                  item.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <!-- 二级权限 -->
                <el-row
                  v-for="items in item.children"
                  :key="items.id"
                  class="secondRow"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="tagClose(scope.row, items.id)"
                    >
                      {{ items.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="13">
                    <el-tag
                      type="warning"
                      v-for="item2 in items.children"
                      :key="item2.id"
                      closable
                      @close="tagClose(scope.row, item2.id)"
                    >
                      {{ item2.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作">
          <template v-slot:default="scope">
            <!-- 编辑按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="small"
              @click="editFormData(scope.row.id)"
              >编辑</el-button
            >
            <!-- 删除按钮 -->
            <el-button
              type="warning"
              icon="el-icon-delete"
              size="small"
              @click="deleteFormData(scope.row.id)"
              >删除</el-button
            >
            <!-- 分配权限按钮 -->
            <el-button
              type="danger"
              icon="el-icon-s-tools"
              size="small"
              @click="treeRights(scope.row)"
            >
              分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRolesDialog"
      width="50%"
      @close="resetAddDialog"
    >
      <el-form
        :model="addRoles"
        :rules="rules"
        ref="addRolesForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色姓名" prop="roleName">
          <el-input v-model="addRoles.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoles.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesDialog = false">取 消</el-button>
        <el-button type="primary" @click="enterAddDialog">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="resetEdiDialog"
    >
      <el-form
        :model="editRoles"
        :rules="rules"
        ref="editRuleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称">
          <el-input v-model="editRoles.roleName" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoles.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="enterEditDialog">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="allotDialog"
      width="50%"
      @close="clearArr"
      ref="treeRef"
    >
      <el-tree
        :data="treeRight"
        :props="defaultProps"
        show-checkbox
        node-key="id"
        :default-expand-all="true"
        :default-checked-keys="treeArr"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="allotDialog = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 请求到的角色列表数据
      rolesData: [],
      // 添加角色表单
      addRoles: {
        roleName: "",
        roleDesc: "",
      },
      // 控制添加角色对话框的显示
      addRolesDialog: false,
      // 控制修改角色对话框的显示
      editDialogVisible: false,
      // 修改角色表单
      editRoles: {
        roleId: "",
        roleName: "",
        roleDesc: "",
      },
      // 控制分配权限对话框
      allotDialog: false,
      // 规则
      rules: {
        roleName: [
          { required: true, message: "请输入角色姓名", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10个字符", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
      },
      // 树形数据
      treeRight: [],
      // tree型匹配规则
      defaultProps: {
        children: "children",
        label: "authName",
      },
      // 默认勾选的权限
      treeArr: [],
      // 分配角色的ID
      roleId: "",
    };
  },
  created() {
    this.getData();
  },
  methods: {
    async getData() {
      const { data: res } = await this.$http.get("roles");
      this.rolesData = res.data;
      console.log(this.rolesData);
    },
    // 重置添加角色表单
    resetAddDialog() {
      this.$refs.addRolesForm.resetFields();
    },
    // 点击添加角色表单确认按钮
    enterAddDialog() {
      // 首先进行表单预校验
      this.$refs.addRolesForm.validate(async (valid) => {
        console.log(valid);
        if (!valid) {
          return this.$message.info("请输入正确信息");
        }
        // 发送网络请求
        const { data: res } = await this.$http.post("roles", this.addRoles);
        this.getData();
        this.addRolesDialog = false;
        console.log(res);
      });
    },
    // 根据ID查询角色
    async editFormData(id) {
      console.log(id);
      const { data: res } = await this.$http.get("roles/" + id);
      this.editRoles = res.data;
      this.editDialogVisible = true;
    },
    // 重置编辑用户表单
    resetEdiDialog() {
      this.$refs.editRuleForm.resetFields();
    },
    // 点击确认按钮提交修改后的表单
    enterEditDialog() {
      // 表单预验证
      this.$refs.editRuleForm.validate(async (valid) => {
        console.log(valid);
        if (!valid) {
          return this.$message.info("请输入正确信息");
        }
        const { data: res } = await this.$http.put(
          "roles/" + this.editRoles.roleId,
          {
            roleName: this.editRoles.roleName,
            roleDesc: this.editRoles.roleDesc,
          }
        );
        console.log(res);
        if (res.meta.status != 200) {
          return this.$message.error(res.meta.msg);
        }
        this.$message.success("修改成功");
        this.getData();
        this.editDialogVisible = false;
      });
    },
    // 点击删除表单按钮
    async deleteFormData(id) {
      console.log(id);
      const ress = await this.$confirm(
        "此操作将永久删除该角色, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      // 点击取消,res 为cancel
      // 点击确认，res为confirm
      if (ress != "confirm") {
        return this.$message.info("取消删除");
      }
      // 发送删除http请求
      const { data: res } = await this.$http.delete("roles/" + id);
      if (res.meta.status != 200) {
        return this.$message.error("删除失败");
      }
      this.$message.success("删除成功");
      this.getData();
      this.editDialogVisible = false;
      console.log(res);
    },
    // 点击删除标签
    async tagClose(role, id) {
      // console.log(role);
      const ress = await this.$confirm(
        "此操作将永久删除该角色, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      // 点击取消,res 为cancel
      // 点击确认，res为confirm
      if (ress !== "confirm") {
        return this.$message.info("取消删除");
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${id}`
      );
      if (res.meta.status != 200) {
        return this.$message.error("删除失败");
      }
      role.children = res.data;
    },
    // 获取所有树形权限
    async treeRights(role) {
      this.roleId = role.id;
      const { data: res } = await this.$http.get("rights/tree");

      if (res.meta.status != 200) {
        return this.$message.error("获取失败");
      }
      // this.$message.success("获取成功");
      this.treeRight = res.data;
      console.log(this.treeRight);
      this.recursion(role, this.treeArr);
      this.allotDialog = true;
    },
    // 递归加入ID
    recursion(node, treeArr) {
      // 没有children则为三级节点  加入数组
      if (!node.children) {
        return treeArr.push(node.id);
      }
      // 否则递归到
      node.children.forEach((item) => {
        this.recursion(item, treeArr);
      });
    },
    // 关闭对话框 数组清空
    clearArr() {
      this.treeArr = [];
    },
    // 点击分配权限对话框确认按钮
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      const str = keys.join(",");
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        {
          rids: str,
        }
      );
      // console.log(keys);
      console.log(res);
      if (res.meta.status != 200) {
        return this.$message.error("分配权限失败");
      }
      this.$message.success("分配权限成功");
      this.getData();
      this.allotDialog = false;
    },
  },
};
</script>

<style lang='less' scoped>
.el-card {
  margin-top: 20px;
}
.el-table {
  margin-top: 20px;
}
.el-tag {
  margin: 10px 0 10px 30px;
}
.scoperow {
  border-bottom: 1px solid #eee;
}
.scoperow:nth-child(1) {
  border-top: 1px solid #eee;
}
.secondRow {
  border-top: 1px solid #eee;
}
.secondRow:nth-child(1) {
  border-top: 0;
}
</style>